package kr.hkit.androidproject_caloriecheck.food;

import java.util.ArrayList;

import kr.hkit.androidproject_caloriecheck.DAO;
import kr.hkit.androidproject_caloriecheck.DBHelper;
import kr.hkit.androidproject_caloriecheck.MyItem;
import kr.hkit.androidproject_caloriecheck.R;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FoodFragment extends Fragment {
	DBHelper mHelper;
	DAO dao;
	ListView list;
	EditText food;
	Button search;
	String eatName;
	int eatKcal;
	int eatSum;
	ArrayList<MyItem> foodEat = new ArrayList<>();
	MyItem foodItem;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View root = inflater.inflate(R.layout.food_add, container, false);

		mHelper = new DBHelper(getActivity());
		dao = DAO.open(getActivity());
		list = (ListView) root.findViewById(R.id.list_food);
		food = (EditText) root.findViewById(R.id.edit_food_add);
		search = (Button) root.findViewById(R.id.btn_food_search);
		search.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ArrayList<MyItem> arList;
				String foodname = food.getText().toString().trim();
				
				if(foodname.equals("")){
					arList = dao.foodSelectAll();
				}else{
					arList = dao.foodSelectByName(foodname);
				}

				if(arList.size() == 0){
					final LinearLayout linear = (LinearLayout) View.inflate(getActivity(), R.layout.food_add02, null);					
					
					new AlertDialog.Builder(getActivity())
					.setTitle("검색결과없음")
					.setView(linear)
					.setPositiveButton("추가", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							EditText foodname = (EditText) linear.findViewById(R.id.edit_foodname);
							EditText foodcal = (EditText) linear.findViewById(R.id.edit_foodcal);
							
							String name = foodname.getText().toString().trim();
							String cal = foodcal.getText().toString().trim();
							
							try {
								validCheck(name, cal);
								dao.foodInsert(name, Integer.parseInt(cal));
								Toast.makeText(getActivity(), name + " " + cal +" 추가", Toast.LENGTH_SHORT).show();
								food.setText("");
							} catch (Exception e) {
								Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
							}

						}
					})
					.setNegativeButton("취소", null)
					.show();
					
				}else{
					MyListAdapter adapter = new MyListAdapter(getActivity(), arList, R.layout.list);
					ListView myList = (ListView) root.findViewById(R.id.list_food);
					myList.setAdapter(adapter);
				}				
			}
		});
		return root;
	}
	
	public void validCheck(String name, String cal) throws Exception {
		if(name.equals("")){
			throw new Exception("음식명을 입력해주세요.");
		}
		if(cal.equals("")){
			throw new Exception("칼로리를 입력해주세요.");
		}
		
		ArrayList<MyItem> arList = dao.foodSelectByName(name);
		if(arList.size() != 0){
			throw new Exception("이미 등록된 정보입니다.");
		}
	}

	class MyListAdapter extends BaseAdapter {
		Context maincon;
		LayoutInflater inflater;
		ArrayList<MyItem> arList;
		int layout;

		public MyListAdapter(Context context, ArrayList<MyItem> arList, int layout) {
			this.maincon = context;
			this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.arList = arList;
			this.layout = layout;
		}

		public int getCount() {
			return arList.size();
		}

		public Object getItem(int position) {
			return arList.get(position).getName();
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			
			if(convertView == null){
				convertView = inflater.inflate(layout, parent, false);
			}
			
			TextView name = (TextView) convertView.findViewById(R.id.name);
			name.setText(arList.get(position).getName());
			
			TextView kcal = (TextView) convertView.findViewById(R.id.kcal);
			kcal.setText(String.valueOf(arList.get(position).getKcal()));
			
			Button add = (Button) convertView.findViewById(R.id.add);
			add.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					eatName = arList.get(pos).getName();
					Toast.makeText(getActivity(),  eatName + " 추가", Toast.LENGTH_SHORT).show();
					
					eatKcal = arList.get(pos).getKcal();
					eatSum += eatKcal;
					
					SharedPreferences pref = getActivity().getSharedPreferences("num", 0);
					SharedPreferences.Editor edit = pref.edit();
					
					edit.putInt("eatKcal", eatKcal);
					edit.putInt("eatSum", eatSum);
					edit.commit();
										
					foodItem = new MyItem(eatName, eatKcal);
					foodEat.add(foodItem);
					
					for(int i=0; i<foodEat.size(); i++){
						Log.d("aaa", foodEat.get(i).getName() + " " + foodEat.get(i).getKcal());
					}
				}
			});
			
			return convertView;
		}
	}
}
